using System.IO;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using GameFrameWork;

[CustomEditor(typeof(UIReuseItem), true)]
class UIReuseItemInspector : Editor
{
    SerializedProperty _script;
    // _variables 已移除，现在使用 UIVariableHelper
    // SerializedProperty _variables;
    SerializedProperty _selectable;

    string _folder;
    string _ctrlPath;
    string _variablePath;

    protected virtual void OnEnable()
    {
        _script = serializedObject.FindProperty("m_Script");
        // _variables 已移除，现在使用 UIVariableHelper
        // _variables = serializedObject.FindProperty("_variables");
        _selectable = serializedObject.FindProperty("_selectable");

        _folder = Path.Combine("Assets/Scripts/UIReuseItems", target.name).Replace('\\', '/').Replace("\\\\", "/");
        _ctrlPath = Path.Combine(_folder, $"{target.name}.cs").Replace('\\', '/').Replace("\\\\", "/");
        _variablePath = Path.Combine(_folder, $"{target.name}.Variable.cs").Replace('\\', '/').Replace("\\\\", "/");
    }
    protected virtual void OnDisable()
    {
        Tools.hidden = false;
    }


    public override void OnInspectorGUI()
    {
        serializedObject.Update();
        EditorGUILayout.BeginVertical("HelpBox");
        {
            EditorGUI.indentLevel++;

            EditorGUI.BeginDisabledGroup(true);
            EditorGUILayout.PropertyField(_script);
            EditorGUI.EndDisabledGroup();

            EditorGUI.indentLevel--;
            EditorGUILayout.EndVertical();
        }


        EditorGUILayout.BeginVertical("HelpBox");
        {
            EditorGUI.indentLevel++;

            EditorGUILayout.PropertyField(_selectable, new GUIContent("Selectable", "是否可被选中"));

            GUILayout.Space(10);

            // Variables 已移除，现在使用 UIVariableHelper
            // 显示 UIVariableHelper 的 Variables
            var uiReuseItem = target as UIReuseItem;
            if (uiReuseItem != null)
            {
                var go = uiReuseItem.gameObject;
                var variableHelper = go.GetComponent<UIVariableHelper>();
                if (variableHelper == null)
                {
                    EditorGUILayout.HelpBox("UIVariableHelper 组件未找到，将在生成脚本时自动添加", MessageType.Info);
                    if (GUILayout.Button("手动添加 UIVariableHelper"))
                    {
                        variableHelper = go.AddComponent<UIVariableHelper>();
                        EditorUtility.SetDirty(go);
                    }
                }
                else
                {
                    EditorGUI.BeginDisabledGroup(true);
                    var helperSerializedObject = new SerializedObject(variableHelper);
                    var helperVariables = helperSerializedObject.FindProperty("m_Variables");
                    EditorGUILayout.PropertyField(helperVariables, new GUIContent("Variables"));
                    helperSerializedObject.ApplyModifiedProperties();
                    EditorGUI.EndDisabledGroup();
                }
            }

            EditorGUI.indentLevel--;
            EditorGUILayout.EndVertical();
        }
        EditorGUILayout.BeginVertical("HelpBox");
        {
            EditorGUI.indentLevel++;

            // ctrl area
            EditorGUILayout.BeginHorizontal();
            var ctrlObj = AssetDatabase.LoadAssetAtPath<Object>(_ctrlPath);
            EditorGUI.BeginDisabledGroup(true);
            EditorGUILayout.LabelField("Controller", GUILayout.Width(100));
            EditorGUILayout.ObjectField(ctrlObj, typeof(Object), true);
            EditorGUI.EndDisabledGroup();
            GUILayout.Space(10);
            EditorGUILayout.Separator();
            EditorGUI.BeginDisabledGroup(!ctrlObj);
            if (GUILayout.Button("Open", GUILayout.Width(50)))
                AssetDatabase.OpenAsset(ctrlObj);
            EditorGUI.EndDisabledGroup();
            EditorGUILayout.EndHorizontal();


            // variable area
            EditorGUILayout.BeginHorizontal();
            var variableObj = AssetDatabase.LoadAssetAtPath<Object>(_variablePath);
            EditorGUI.BeginDisabledGroup(true);
            EditorGUILayout.LabelField("Variable", GUILayout.Width(100));
            EditorGUILayout.ObjectField(variableObj, typeof(Object), true);
            EditorGUI.EndDisabledGroup();
            GUILayout.Space(10);
            EditorGUILayout.Separator();
            EditorGUI.BeginDisabledGroup(!variableObj);
            if (GUILayout.Button("Open", GUILayout.Width(50)))
                AssetDatabase.OpenAsset(variableObj);
            EditorGUI.EndDisabledGroup();
            EditorGUILayout.EndHorizontal();

            EditorGUI.indentLevel--;
            EditorGUILayout.EndVertical();
        }

        EditorGUILayout.BeginVertical("HelpBox");
        {
            EditorGUI.indentLevel++;

            DrawGenerateBtn();

            EditorGUI.indentLevel--;
            EditorGUILayout.EndVertical();
        }
        serializedObject.ApplyModifiedProperties();
    }


    void DrawGenerateBtn()
    {
        GUIStyle style = new GUIStyle("Button")
        {
            alignment = TextAnchor.MiddleCenter,
            fontStyle = FontStyle.BoldAndItalic,
            fontSize = 15,
        };
        GUI.color = Color.green;
        if (GUILayout.Button("Generate", style, GUILayout.Height(25)))
        {
            GenerateScripts(serializedObject.targetObject);
        }
        GUI.color = Color.white;
    }

    void GenerateScripts(Object target)
    {
        var go = GetGameObject(target);
        if (go)
        {
            // 确保有 UIVariableHelper 组件
            var variableHelper = go.GetComponent<UIVariableHelper>();
            if (variableHelper == null)
            {
                variableHelper = go.AddComponent<UIVariableHelper>();
                EditorUtility.SetDirty(go);
            }

            try
            {
                // 使用 UIVariableGenerator 生成脚本（统一使用新的生成方式）
                var menuCommand = new MenuCommand(go);
                UIVariableGenerator.GenerateVariableScript(menuCommand);
                
                EditorUtility.SetDirty(go);
                var stage = PrefabStageUtility.GetCurrentPrefabStage();
                if (stage)
                {
                    PrefabUtility.SaveAsPrefabAsset(stage.prefabContentsRoot, stage.assetPath);
                    stage.ClearDirtiness();
                }

                Debug.Log($"{go.name} - 脚本生成成功（使用 UIVariableGenerator）");

            }
            catch (System.Exception e)
            {
                EditorUtility.DisplayDialog("错误", $"生成脚本失败: {e.Message}", "确定");
                Debug.LogError($"生成脚本失败: {e.Message}\n{e.StackTrace}");
            }
        }
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }

    GameObject GetGameObject(Object target)
    {
        GameObject targetGameObject;
        if (target is Component component)
        {
            targetGameObject = component.gameObject;
        }
        else if (target is GameObject gameObject)
        {
            targetGameObject = gameObject;
        }
        else
        {
            targetGameObject = null;
        }
        return targetGameObject;
    }
}
